package com.remoter.transport.socket.codec;

import java.io.ByteArrayInputStream;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.remoter.basic.bean.AbstractMessage;
import com.remoter.basic.serialize.ISerialization;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

/**
 * @author			koko
 * @date 			2017-08-09 09:21:13
 * @description 	类功能说明
 */
public class MessageDecoder extends ByteToMessageDecoder{
	
	private static final Logger logger = LoggerFactory.getLogger(MessageDecoder.class);
	private ISerialization serialization;
	private Class<?> type;
	public MessageDecoder(ISerialization serialization,Class<?> type){
		this.serialization = serialization;
		this.type = type;
	}
	
	@Override
	protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
		if(in.readableBytes() < AbstractMessage.MESSAGE_LENGTH){
			return;
		}
		in.markReaderIndex();
		int length = in.readInt();
		if(length < 0){
			ctx.close();
		}
		if(in.readableBytes() < length){
			in.resetReaderIndex();
			return;
		}else{
			byte[] content = new byte[length];
			in.readBytes(content);
			try(ByteArrayInputStream bais = new ByteArrayInputStream(content)){
				Object obj = this.serialization.deserialize(bais,this.type);
				out.add(obj);
			}catch(Exception e){
				logger.error(e.getMessage(),e);
			}
		}
	}
	
}